﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Yipusoft.MapInfo;
using Yipusoft.MapInfo.BLL;
using System.IO;
using Yipusoft.MapInfo.Model;
using System.Collections.Generic;


public partial class MapInfo_DepartmentManager : System.Web.UI.Page
{
    private string photoUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Bind(0);
            GridBind(Request["DepartmentID"]);
            BindClass();
            Yipusoft.Listener.Model.Departments departmentMap = Yipusoft.Listener.BLL.Department.GetModel(Request["DepartmentID"]);
            if (departmentMap != null)
            {
                DptSmall.SelectedValue = departmentMap.DepartmentID;
                txtDepartmentName.Text = departmentMap.DepartmentName;
                dptDepartmentType.SelectedValue = departmentMap.DepartmentType;
                txtAddress.Text = departmentMap.Address;
                txtAreaSize.Text = departmentMap.AreaSize.ToString();
                txtCreateTime.Text = departmentMap.BuildTime.Value.ToShortDateString();
                //txtInfoName.Text = departmentMap.CommName;
                txtPhone.Text = departmentMap.ContactPhone;
                txtContractCount.Text = departmentMap.ContractNumber.Value.ToString();
                txtCadreCount.Text = departmentMap.CadreNumber.Value.ToString();
                CombatCount1.Text = departmentMap.FighterNumber.Value.ToString();
                txtGroupNumber.Text = departmentMap.GroupNumber.Value.ToString();
                txtLog.Text = departmentMap.Longitude.Value.ToString();
                txtLat.Text = departmentMap.Latitude.Value.ToString();
                txtTName.Text = departmentMap.LeadName;
                txtPost.Text = departmentMap.Zip;
                txtSoldiersCount.Text = departmentMap.SoldierNumber.Value.ToString();
                DptFireType.SelectedValue = departmentMap.StationType;
                DptLevel.SelectedValue = departmentMap.StationLevel;

                


            }

        }
        if (!Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "400242"))
        {
            // Response.Write("<script>alert('没有权限！');history.back(0);</script>");
        }

    }

    private void BindClass()
    {
        string DepartmentID = Request["DepartmentID"];
        string Where = "";
        if (DepartmentID.Substring(4, 1).Equals("2"))
            Where = " GroupID='KSTP' And ParentID='KS0001' Order By ItemID";

        if (DepartmentID.Substring(4, 1).Equals("3") || DepartmentID.Substring(4, 1).Equals("1"))
            Where = " GroupID='KSTP' And ParentID='KS0000' Order By ItemID";

        List<Yipusoft.Common.Model.CodeItemInfo> list = Yipusoft.Common.BLL.CodeItem.GetList2(Where);
        this.ddlPhotoName.DataSource = list;
        this.ddlPhotoName.DataTextField = "ItemName";
        this.ddlPhotoName.DataValueField = "ItemID";
        this.ddlPhotoName.DataBind();

    }
    public void ListPageContral1_PageSizeChange(int pageSize, int PageIndex)
    {
        Bind(PageIndex);
    }

    private void GridBind(string departmentID)
    {
        //btnSave.Visible = IsTrue();
        //btnUpLoad.Visible = IsTrue();

        Bind(0);
        this.DptBig.DataSource = Yipusoft.Account.BLL.Department.GetList(" Right(DepartmentID,2)='00'");
        this.DptBig.DataTextField = "FullName";
        this.DptBig.DataValueField = "DepartmentID";
        this.DptBig.DataBind();


        Yipusoft.Account.Model.DepartmentInfo info = Yipusoft.Account.BLL.Department.GetDepartment(Request["DepartmentID"]);
        //if (info != null)
        //{
        //    this.ddlPhotoName.Items.Insert(0, new ListItem(info.FullName, info.FullName));
        //}

        this.DptFireType.DataSource = Yipusoft.Common.BLL.CodeItem.GetList2(" GroupID='XFZLB'");
        this.DptFireType.DataTextField = "ItemName";
        this.DptFireType.DataValueField = "ItemID";
        this.DptFireType.DataBind();

        this.DptLevel.DataSource = Yipusoft.Common.BLL.CodeItem.GetList2(" GroupID='XFZDJ'");
        this.DptLevel.DataTextField = "ItemName";
        this.DptLevel.DataValueField = "ItemID";
        this.DptLevel.DataBind();


        DptBig.Items.Insert(0, new ListItem("请选择单位", "00"));
        List<DepartmentPhotoInfo> departmentPhotos = DepartmentPhoto.GetPhotoListByDepartmentID(departmentID);
        //gvDepartmentPhoto.DataSource = DepartmentPhoto.GetPhotoListByDepartmentID(departmentID);
        //gvDepartmentPhoto.DataBind();
        if (Request["DepartmentID"] != null)
        {
            if ((!Request["DepartmentID"].Substring(0, 4).Equals("13121")) && (!Request["DepartmentID"].Substring(0, 4).Equals("13131")))
            {
                this.DptBig.SelectedValue = Request["DepartmentID"].Substring(0, 4) + "000";
            }
            else
            {
                this.DptBig.SelectedValue = Request["DepartmentID"].Substring(0, 5) + "00";
            }
            this.DptBig_SelectedIndexChanged(this.DptBig, new EventArgs());
            this.DptSmall.SelectedValue = Request["DepartmentID"];
            this.txtDepartmentName.Text = DptSmall.SelectedItem.Text;
        }


    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        int _limitwidth = 800;
        int _limitheight = 600;

        if (fuDepartmentPhoto.FileName != "" && fuDepartmentPhoto.PostedFile.ContentLength > 0)
        {
            try
            {
                // if not already present, create a directory named /Uploads/<CurrentUserName>
                string filename = fuDepartmentPhoto.FileName.ToLower();
                int i = filename.LastIndexOf(".");
                filename = filename.Substring(i, filename.Length - i);

                if (!(filename == ".jpg" || filename == ".jpeg" || filename == ".gif" || filename == ".png" || filename == ".bmp"))
                {

                    lblInfo.Text = "不受支持的类型,请重新选择!";

                }//检查上传文件的格式是否有效
                else
                {
                    Stream oStream = fuDepartmentPhoto.PostedFile.InputStream;
                    System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

                    int owidth = oImage.Width; //原图宽度
                    int oheight = oImage.Height; //原图高度

                    if (owidth > _limitwidth || oheight > _limitheight)
                    {

                        lblInfo.Text = "超过允许的图片尺寸(" + _limitwidth.ToString() + "×" + _limitheight.ToString() + ")范围!";

                    }//检查是否超出规定尺寸
                    else
                    {
                        photoUrl = "";
                        string dirUrl = this.Request.ApplicationPath +
                           "Uploads/" + Request["departmentID"];
                        string dirPath = Server.MapPath(dirUrl);
                        if (!Directory.Exists(dirPath))
                            Directory.CreateDirectory(dirPath);
                        // save the file under the user's personal folder
                        string fileUrl = dirUrl + "/" + Path.GetFileName(fuDepartmentPhoto.PostedFile.FileName);
                        fuDepartmentPhoto.PostedFile.SaveAs(Server.MapPath(fileUrl));
                        //Profile.Initialize(this.Page.User.Identity.Name, true);
                        photoUrl = fileUrl;
                        //string DepartmentType = dptDepartmentType.SelectedValue;




                    }
                }
            }
            catch (Exception ex)
            {

                lblInfo.Text = ex.Message;
            }
        }
        try
        {
            Yipusoft.Listener.Model.Departments model = Yipusoft.Listener.BLL.Department.GetModel(Request["DepartmentID"]);

            Yipusoft.Listener.Model.Departments Department = new Yipusoft.Listener.Model.Departments();
            Department.DepartmentID = DptSmall.SelectedValue;
            Department.DepartmentName = txtDepartmentName.Text.Trim();
            Department.DepartmentType = dptDepartmentType.SelectedValue;
            Department.Address = txtAddress.Text.Trim();
            Department.AreaSize = int.Parse(txtAreaSize.Text.Trim() != "" ? txtAreaSize.Text.Trim() : "0");
            Department.BuildTime = DateTime.Parse(txtCreateTime.Text.Trim() != "" ? txtCreateTime.Text.Trim() : DateTime.Now.ToShortDateString());
            Department.CommName = "";
            Department.ContactPhone = txtPhone.Text.Trim();
            Department.ContractNumber = int.Parse(txtContractCount.Text.Trim() != "" ? txtContractCount.Text.Trim() : "0");
            Department.CadreNumber = int.Parse(txtCadreCount.Text.Trim() != "" ? txtCadreCount.Text.Trim() : "0");
            Department.FighterNumber = int.Parse(CombatCount1.Text.Trim() != "" ? CombatCount1.Text.Trim() : "0");
            Department.GroupNumber = int.Parse(txtGroupNumber.Text.Trim() != "" ? txtGroupNumber.Text.Trim() : "0");
            Department.Longitude = decimal.Parse(txtLog.Text.Trim() != "" ? txtLog.Text.Trim() : "0");
            Department.Latitude = decimal.Parse(txtLat.Text.Trim() != "" ? txtLat.Text.Trim() : "0");
            Department.LeadName = txtTName.Text;
            Department.ParentID = "";
            Department.Zip = txtPost.Text;
            Department.TimeLastModified = DateTime.Now;
            Department.SoldierNumber = int.Parse(txtSoldiersCount.Text.Trim() != "" ? txtSoldiersCount.Text.Trim() : "0");
            Department.StationType = DptFireType.SelectedValue;
            Department.StationLevel = DptLevel.SelectedValue;
            Department.DepartmentPhoto = photoUrl;

            if (model == null)
            {
                if (Yipusoft.Listener.BLL.Department.Add(Department) > 0)
                {
                    lblInfo.Text = "基本信息保存成功。";
                }
                else
                {
                    lblInfo.Text = "操作失败";
                }
            }
            else
            {
                if (Yipusoft.Listener.BLL.Department.Update(Department) > 0)
                {
                    lblInfo.Text = "基本信息更新成功。";
                }
                else
                {
                    lblInfo.Text = "操作失败";
                }
            }
        }
        catch (Exception ex) { lblInfo.Text = ex.Message.ToString(); };

    }

    public void btnDelete_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandArgument == null)
            return;
        DepartmentPhoto.DeleteDepartmentPhoto(e.CommandArgument.ToString());
        GridBind(Request["departmentID"]);
    }

    public void btnEdit_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandArgument == null)
            return;
        DepartmentPhotoInfo departmentPhotos = DepartmentPhoto.GetDepartmentPhotoInfoByID(e.CommandArgument.ToString());
        if (departmentPhotos == null)
            return;

        this.ddlPhotoName.SelectedItem.Text = departmentPhotos.PhotoName;

        txtPhotoDetails.Text = departmentPhotos.PhotoDetails;
        btnUpLoad.Text = "更新";
        btnUpLoad.CommandArgument = departmentPhotos.PhotoID;
    }


    protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        int _limitwidth = 800;
        int _limitheight = 600;
        string photoUrl = "";
        if (fuPhoto.PostedFile != null && fuPhoto.PostedFile.ContentLength > 0)
        {
            try
            {
                // if not already present, create a directory named /Uploads/<CurrentUserName>
                string filename = fuPhoto.FileName.ToLower();
                int i = filename.LastIndexOf(".");
                filename = filename.Substring(i, filename.Length - i);

                if (!(filename == ".jpg" || filename == ".jpeg" || filename == ".gif" || filename == ".png" || filename == ".bmp"))
                {

                    lblimginfo.Text = "不受支持的类型,请重新选择!";

                }//检查上传文件的格式是否有效
                else
                {

                    Stream oStream = fuPhoto.PostedFile.InputStream;
                    System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

                    int owidth = oImage.Width; //原图宽度
                    int oheight = oImage.Height; //原图高度

                    if (owidth > _limitwidth || oheight > _limitheight)
                    {

                        lblimginfo.Text = "超过允许的图片尺寸(" + _limitwidth.ToString() + "×" + _limitheight.ToString() + ")范围!";

                    }//检查是否超出规定尺寸
                    else
                    {
                        string dirUrl = this.Request.ApplicationPath +
                           "Uploads/" + Request["departmentID"];
                        string dirPath = Server.MapPath(dirUrl);
                        if (!Directory.Exists(dirPath))
                            Directory.CreateDirectory(dirPath);
                        // save the file under the user's personal folder
                        //string fileUrl = dirUrl + "/" + Path.GetFileName(fuPhoto.PostedFile.FileName);
                        string fileUrl = dirUrl + "/" + DateTime.Now.ToString("msyyyyMMddhhmmssms") + filename;

                        fuPhoto.PostedFile.SaveAs(Server.MapPath(fileUrl));
                        //Profile.Initialize(this.Page.User.Identity.Name, true);
                        photoUrl = fileUrl;

                        List<Yipusoft.MapInfo.Model.DepartmentPhotoInfo> list2= DepartmentPhoto.GetPhotoByDepartmentID(" DepartmentID='" + Request["departmentID"] + "' And PhotoName='" + ddlPhotoName.SelectedValue + "'", "PhotoName", "ASC", 10, 0);
                        if (list2 == null || list2.Count > 0)
                        {
                            lblimginfo.Text = "该室图片已存在请删除后在上传";
                            return;
                        }
                        if (btnUpLoad.Text.Trim().Equals("更新") && btnUpLoad.CommandArgument != null)
                        {
                            DepartmentPhotoInfo departmentPhotos = DepartmentPhoto.GetDepartmentPhotoInfoByID(btnUpLoad.CommandArgument);
                            if (departmentPhotos == null)
                            {
                                lblimginfo.Text = "图片信息更新失败";
                                return;
                            }
                            departmentPhotos.PhotoUrl = photoUrl;
                            departmentPhotos.DepartmentID = this.DptSmall.SelectedValue;
                            departmentPhotos.PhotoDetails = txtPhotoDetails.Text;
                            departmentPhotos.OrderID = ddlPhotoName.SelectedIndex;
                            if (DepartmentPhoto.UpdateDepartmentPhoto(departmentPhotos) > 0)
                            {
                                lblimginfo.Text = "图片信息更新成功。";
                                hidphotoid.Value = "";
                                btnUpLoad.Text = "上传";
                                btnUpLoad.CommandName = "";
                                GridBind(Request["DepartmentID"]);
                            }
                        }
                        else
                        {
                            if (DepartmentPhoto.InsertDepartmentPhoto(DptSmall.SelectedValue, ddlPhotoName.SelectedValue, photoUrl, txtPhotoDetails.Text, ddlPhotoName.SelectedIndex) > 0)
                            {
                                lblimginfo.Text = "图片信息保存成功。";
                                GridBind(Request["DepartmentID"]);
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {

                lblimginfo.Text = ex.Message;
            }
        }
        else
        {

        }
    }

    public string GetItemName(object objID)
    {
        
        if (objID == null)
            return "";

        try
        {
         Yipusoft.Common.Model.CodeItemInfo info=  Yipusoft.Common.BLL.CodeItem.GetCodeItem(objID.ToString().Trim(),"KSTP");
         if (info == null)
             return "";
         return info.ItemName;
        }
        catch { return ""; };
    }
    private void Bind(int pageindex)
    {
        string DepartmentID = string.Empty;
        if (Request["DepartmentID"] != null)
        {
            if (!Request["DepartmentID"].Substring(0, 2).Equals("13"))
                DepartmentID = "13" + Request["DepartmentID"];
            else
                DepartmentID = Request["DepartmentID"];

            List<Yipusoft.MapInfo.Model.DepartmentPhotoInfo> list = Yipusoft.MapInfo.BLL.DepartmentPhoto.GetPhotoByDepartmentID("DepartmentId='" + DepartmentID + "'", "OrderID", "ASC", 8, pageindex);
            if (list == null)
                return;

            this.DltList.DataSource = list;
            this.ListPageContral1.ItemCount = Yipusoft.MapInfo.BLL.DepartmentPhoto.GetPhotoListByDepartmentID(DepartmentID).Count();
            this.DltList.DataBind();


        }
    }

    protected void gvDepartmentPhoto_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void DptBig_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DptBig.Items.Count <= 0)
            return;
        this.DptSmall.DataSource = Yipusoft.Account.BLL.Department.GetList("Left(DepartmentID,4)='" + DptBig.SelectedValue.Substring(0, 4) + "'");
        this.DptSmall.DataTextField = "FullName";
        this.DptSmall.DataValueField = "DepartmentID";
        this.DptSmall.DataBind();
        this.txtDepartmentName.Text = DptSmall.SelectedItem.Text;

    }
    public bool IsTrue()
    {
        return Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "500002");
    }
    protected void DptSmall_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.txtDepartmentName.Text = DptSmall.SelectedItem.Text;
    }
}

